<template>
    <!-- BaikeArticleList -->
    <div class="infinite-list">
        <div class="search-box" style="margin-bottom: 20px;">
            <el-row :gutter="20">
                <el-col :span="18">
                    <el-input
                        v-model="searchKeyword"
                        placeholder="请输入搜索关键词"
                        class="input-with-select"
                        @keyup.enter="handleSearch"
                    >
                        <template #append>
                            <el-button @click="handleSearch">
                                <el-icon><Search /></el-icon>
                            </el-button>
                        </template>
                    </el-input>
                </el-col>
                <el-col :span="6">
                    <el-select v-model="selectedCategory" placeholder="选择分类" @change="handleCategoryChange" style="width: 100%;">
                        <el-option label="全部" value="全部" />
                        <el-option v-for="category in categories" :key="category" :label="category" :value="category" />
                    </el-select>
                </el-col>
            </el-row>
        </div>
        <el-card v-for="(item, index) in articles" :key="index" style="max-height: 250px;margin-bottom: 10px;">
            <el-row>
                <el-col :span="6" style="max-height: 250px;">
                    <!-- 图片位置 -->
                    <el-image style="height: 100%; width: 100%;object-fit: scale-down;" :src="item.img" fit="fill"
                        :lazy="true"></el-image>
                </el-col>
                <el-col :span="18">
                    <div class="text-box">
                        <el-link type="primary" :underline="false" :href="openArticleLike(item.id)" target="_blank">
                            <div class="text-title">{{ item.title }}</div>
                        </el-link><br>
                        <el-text truncated line-clamp="3" class="text-content" style="word-wrap: break-word;">
                            {{ item.content }}
                        </el-text>
                        <div class="text-date"><el-icon>
                                <Timer />
                            </el-icon>{{ item.view_date }}</div>
                    </div>
                </el-col>
            </el-row>
        </el-card>
        <div class="demo-pagination-block">
            <div class="demonstration" style="margin-top: 50px;"></div>
            <el-pagination v-model:current-page="page" :background="true" layout="prev, pager, next, jumper"
                :total="total" @current-change="handleCurrentChange" />
        </div>
    </div>
</template>

<script setup>
import { getArticleNum, getBaikeArticleList, searchArticles, getCategories } from '@/api/baike';
import { getimage } from '@/api/image';
import { onMounted, ref } from 'vue';
import { Search } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';



const articles = ref([]);
let page = ref(1);
const total = ref(0);
let num = ref(10);
const searchKeyword = ref('');
const selectedCategory = ref('全部');
const categories = ref([]);

const loadCategories = async () => {
    try {
        const res = await getCategories();
        if (res.data.code === 200) {
            categories.value = res.data.data;
        }
    } catch (error) {
        console.error('Error loading categories:', error);
    }
};
// 分类选择变化
const handleCategoryChange = () => {
    page.value = 1;
    syncArticles();
};

const syncArticles = async () => {
    try {
        let res;
        if (searchKeyword.value || selectedCategory.value !== '全部') {
            res = await searchArticles(
                searchKeyword.value || '-', // 使用'-'代替空字符串
                selectedCategory.value, 
                page.value, 
                num.value
            );
            if (res.data.code === 200) {
                total.value = res.data.total;
                articles.value = res.data.data.map(e => ({
                    ...e,
                    img: getimage(e.img),
                    content: e.content || '',
                    view_date: e.view_date
                }));
            } else {
                ElMessage.warning(res.data.message || '获取文章列表失败');
            }
        } else {
            res = await getBaikeArticleList(page.value, num.value);
            const res1 = await getArticleNum();
            total.value = res1.data.data;
            articles.value = res.data.data.map(e => ({
                ...e,
                img: getimage(e.img),
                content: e.content || '',
                view_date: e.view_date
            }));
        }
    } catch (error) {
        console.error('Error fetching articles:', error);
        if (error.response) {
            ElMessage.error(error.response.data.message || '服务器响应错误');
        } else {
            ElMessage.error('网络请求失败，请稍后重试');
        }
    }
};
// 关键字搜索
const handleSearch = () => {
    page.value = 1;
    syncArticles();
};
// 分页
const handleCurrentChange = (val) => {
    console.log(`current page: ${val}`)
    page.value = val;
    syncArticles();
    window.scrollTo({ top: 0, behavior: 'smooth' });
}

onMounted(() => {
    loadCategories();
    syncArticles(page.value, num.value);
})

const openArticleLike = (id) => {

    return '/article/' + id
}


</script>

<style scoped>
.infinite-list {
    min-height: 100vh;
    padding: 0;
    margin: 10px 0 0 0;
    list-style: none;
    overflow-x: hidden;
}

.text-box {
    padding: 10px;
}

.text-title {
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 10px;
    color: #333;
}

.text-content {
    font-size: 14px;
    color: #666;
    line-height: 1.5;
}

.text-date {
    font-size: 12px;
    color: #999;
    margin-top: 10px;
}

/* 响应式布局 */
@media screen and (max-width: 768px) {
    .search-box {
        margin-bottom: 15px;
    }
    
    .el-row {
        margin: 0 !important;
    }
    
    .el-col {
        padding: 0 !important;
    }
    
    .el-col-18, .el-col-6 {
        width: 100%;
        margin-bottom: 10px;
    }
    
    .el-card {
        margin-bottom: 15px;
    }
    
    .el-card .el-row .el-col-6,
    .el-card .el-row .el-col-18 {
        width: 100%;
    }
    
    .el-image {
        max-height: 200px;
        margin-bottom: 10px;
    }
    
    .text-title {
        font-size: 16px;
    }
    
    .text-content {
        font-size: 13px;
    }
    
    .demo-pagination-block {
        margin-top: 20px;
        text-align: center;
    }
    
    .el-pagination {
        justify-content: center;
        flex-wrap: wrap;
    }
}

@media screen and (max-width: 480px) {
    .infinite-list {
        margin: 5px 0 0 0;
    }
    
    .text-title {
        font-size: 15px;
    }
    
    .text-content {
        font-size: 12px;
    }
    
    .el-pagination {
        font-size: 12px;
    }
}
</style>